package com.mlizhi.modules.spec;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mlizhi.base.MlzApplication;
import com.mlizhi.base.VersionManager;
import com.mlizhi.kingdom.R;
import com.mlizhi.modules.spec.detect.SpecDetectFragment;
import com.mlizhi.modules.spec.detect.ble.BluetoothLeService;
import com.mlizhi.modules.spec.record.SpecRecordFragment;
import com.mlizhi.modules.spec.setting.SpecSettingFragment;
import com.mlizhi.utils.Constants;

import java.util.List;
import java.util.UUID;

@SuppressLint("NewApi")
public class SpecActivity extends FragmentActivity implements ISpecInterface,IRegInterface {

	
	//**************测水开始
	private BluetoothManager mBluetoothManager;
	private BluetoothAdapter mBluetoothAdapter;
	private boolean enable = false;
	private static final int REQUEST_ENABLE_BT_CLICK = 3;
	private boolean supportBle = false;
	//******************测水结束
	private TextView testStatusTextView;
	private String testStatus = "";
	
	// 检测页面左上角的info图标
	private ImageView specInfoImageView;
	// 主页面的标题
	private TextView specTitleTextView;
	// 主页面的标题区域
	private RelativeLayout specTitleLayout;
	//title下面的分割线
	private View specTitleDeliverView;
	// 菜单组
	private RadioGroup specNavRadioGroup;
	// 资讯页面
//	private SpecContentFragment specContentFragment;
	// 检测页面
	private SpecDetectFragment specDetectFragment;
	// 历史记录页面
	private SpecRecordFragment specRecordFragment;
	// 个人中心页面
	private SpecSettingFragment specSettingFragment;
	
//	//资讯页面ViewId
//	public static final int SPEC_CONTENT_VIEW_ID = 0x001;
	//检测页面ViewId
	public static final int SPEC_DETECT_VIEW_ID = 0x002;
	//历史记录页面ViewId
	public static final int SPEC_RECORD_VIEW_ID = 0x003;
	// 个人中心页面ViewId
	public static final int SPEC_SETTING_VIEW_ID = 0x004;

	// Fragment 事务处理器
	FragmentTransaction ft = null;
	private Context mContext;
	private MlzApplication mlzApplication;

	public BroadcastReceiver mGattUpdateReceiver = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;
		activity = this;
		mlzApplication = (MlzApplication) getApplication();
		setContentView(R.layout.activity_spec);
		specInfoImageView = (ImageView) findViewById(R.id.id_spec_icon_iv);
		specTitleTextView = (TextView) findViewById(R.id.id_spec_title_tv);
		specNavRadioGroup = (RadioGroup) findViewById(R.id.id_spec_nav_view_group);
		specTitleLayout = (RelativeLayout) findViewById(R.id.id_spec_title_ly);
		specTitleDeliverView =  findViewById(R.id.id_spec_title_deliver);
		testStatusTextView = findViewById(R.id.id_ble_test_textView);
		initView();
		initBle();
		Intent gattServiceIntent = new Intent(SpecActivity.this, BluetoothLeService.class);
		bindService(gattServiceIntent, mServiceConnection,Activity.BIND_AUTO_CREATE);
		mGattUpdateReceiver = specDetectFragment.new BleBroadcastReceiver();
		registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
		//注册蓝牙接收器
		if(supportBle){
			receiverReleased = false;
			scanLeDevice(true);
		}
		new VersionManager(this).showVersionProcessDialog(true);
	}

	/**
	 * 初始化各个主页面，并赋默认值
	 */
	private void initView() {
//		specContentFragment = SpecContentFragment.getNewInstance();
		specDetectFragment = SpecDetectFragment.getNewInstance();
		specRecordFragment = SpecRecordFragment.getNewInstance();
		specSettingFragment = SpecSettingFragment.getNewInstance();
		// =============设置默认页面开始========
		ft = getSupportFragmentManager().beginTransaction();
		// 替换一个已经存在的Fragment，在替换时候同时调用remove在该容器中已经添加的Fragment
		ft.replace(R.id.id_spec_content_view, specDetectFragment);
		// //可以重复添加View到Fragment容器中
		// ft.add(fragmentContentId, loadingViewFragment);
		ft.commit();
		specNavRadioGroup.check(R.id.id_nav_detect_btn);
		specTitleTextView.setText(R.string.nav_detect);
		specTitleTextView.setTextColor(getResources().getColor(R.color.font_primary_color));
		specInfoImageView.setVisibility(View.VISIBLE);
//		specTitleDeliverView.setVisibility(View.GONE);
		// =============设置默认页面结束=========
	}

	/**
	 * 设置菜单控制器
	 */
	public void switchViewController(View view) {

		specInfoImageView.setVisibility(View.GONE);
		switch (view.getId()) {
//		case R.id.id_nav_content_btn://切换到资讯页面
//			ft = getSupportFragmentManager().beginTransaction();
//			ft.replace(R.id.id_spec_content_view, specContentFragment);
//			ft.commit();
//			specNavRadioGroup.check(R.id.id_nav_content_btn);
//			specTitleTextView.setText(R.string.nav_content);
//			specTitleLayout.setBackgroundColor(Color.parseColor("#20bfbf"));
//			specTitleTextView.setTextColor(getResources().getColor(R.color.theme_primary_white));
////			specTitleDeliverView.setVisibility(View.VISIBLE);
//			break;
		case R.id.id_nav_detect_btn://切换到检测页面
			ft = getSupportFragmentManager().beginTransaction();
			ft.replace(R.id.id_spec_content_view, specDetectFragment);
			ft.commit();
			specNavRadioGroup.check(R.id.id_nav_detect_btn);
			specTitleTextView.setText(R.string.nav_detect);
			specTitleLayout.setBackgroundColor(Color.WHITE);
			specTitleTextView.setTextColor(getResources().getColor(R.color.font_primary_color));
			specInfoImageView.setVisibility(View.VISIBLE);
//			specTitleDeliverView.setVisibility(View.GONE);
			break;
		case R.id.id_nav_record_btn://切换到历史记录页面
			ft = getSupportFragmentManager().beginTransaction();
			ft.replace(R.id.id_spec_content_view, specRecordFragment);
			ft.commit();
			specNavRadioGroup.check(R.id.id_nav_record_btn);
			specTitleTextView.setText(R.string.nav_record);
			specTitleLayout.setBackgroundColor(Color.WHITE);
			specTitleTextView.setTextColor(getResources().getColor(R.color.font_primary_color));
//			specTitleDeliverView.setVisibility(View.VISIBLE);
			break;
		case R.id.id_nav_setting_btn://切换到个人中心页面
			ft = getSupportFragmentManager().beginTransaction();
			ft.replace(R.id.id_spec_content_view, specSettingFragment);
			ft.commit();
			specNavRadioGroup.check(R.id.id_nav_setting_btn);
			specTitleTextView.setText(R.string.nav_setting_title);
			specTitleLayout.setBackgroundColor(Color.WHITE);
			specTitleTextView.setTextColor(getResources().getColor(R.color.font_primary_color));
//			specTitleDeliverView.setVisibility(View.VISIBLE);
			break;
			
		default://默认是切换到检测页面
			ft = getSupportFragmentManager().beginTransaction();
			ft.replace(R.id.id_spec_content_view, specDetectFragment);
			ft.commit();
			specNavRadioGroup.check(R.id.id_nav_detect_btn);
			specTitleTextView.setText(R.string.nav_detect);
			specTitleLayout.setBackgroundColor(Color.WHITE);
			specTitleTextView.setTextColor(getResources().getColor(R.color.font_primary_color));
			specInfoImageView.setVisibility(View.VISIBLE);
//			specTitleDeliverView.setVisibility(View.GONE);
			break;
		}
	}

	

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
	}

	/**
	 * 页面
	 */
	public void onViewClick(View view) {
		Intent intent = new Intent(this,CommonQuestionActivity.class);
		startActivity(intent);
	}
	
	
	@Override
	public void switchSpecViewById(int viewId) {
		ft = getSupportFragmentManager().beginTransaction();
		specInfoImageView.setVisibility(View.GONE);
		specNavRadioGroup.setVisibility(View.VISIBLE);
		switch (viewId) {
		
//		case SPEC_CONTENT_VIEW_ID://切换到资讯页面
//			ft.replace(R.id.id_spec_content_view, specContentFragment);
//			specNavRadioGroup.check(R.id.id_nav_content_btn);
//			specTitleTextView.setText(R.string.nav_content);
//			specTitleLayout.setBackgroundColor(Color.parseColor("#20bfbf"));
//			specTitleTextView.setTextColor(getResources().getColor(R.color.theme_primary_white));
////			specTitleDeliverView.setVisibility(View.VISIBLE);
//			break;
		case SPEC_DETECT_VIEW_ID://切换到检测页面
			ft.replace(R.id.id_spec_content_view, specDetectFragment);
			specNavRadioGroup.check(R.id.id_nav_detect_btn);
			specTitleTextView.setText(R.string.nav_detect);
			specTitleLayout.setBackgroundColor(Color.WHITE);
			specInfoImageView.setVisibility(View.VISIBLE);
			specTitleTextView.setTextColor(getResources().getColor(R.color.font_primary_color));
//			specTitleDeliverView.setVisibility(View.GONE);
			break;
		case SPEC_RECORD_VIEW_ID://切换到历史记录页面
			ft.replace(R.id.id_spec_content_view, specRecordFragment);
			specNavRadioGroup.check(R.id.id_nav_record_btn);
			specTitleTextView.setText(R.string.nav_record);
			specTitleLayout.setBackgroundColor(Color.WHITE);
			specTitleTextView.setTextColor(getResources().getColor(R.color.font_primary_color));
//			specTitleDeliverView.setVisibility(View.VISIBLE);
			break;
		case SPEC_SETTING_VIEW_ID://切换到个人中心页面
			ft.replace(R.id.id_spec_content_view, specSettingFragment);
			specNavRadioGroup.check(R.id.id_nav_setting_btn);
			specTitleTextView.setText(R.string.nav_setting_title);
			specTitleLayout.setBackgroundColor(Color.WHITE);
			specTitleTextView.setTextColor(getResources().getColor(R.color.font_primary_color));
//			specTitleDeliverView.setVisibility(View.VISIBLE);
			break;

		}
		ft.commit();
	}

	
	
	
//	@Override
//	public void setTitleVisiblity(int visiblity) {
//		specTitleLy.setVisibility(visiblity);
//	}
//
//	@Override
//	public void setBottomVisiblity(int visiblity) {
//		specNavRadioGroup.setVisibility(visiblity);
//	}

	public void initBle() {
		// 获取当前系统版本号（android4.3的版本号为18）
        int currentApiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentApiVersion < 18) {
            supportBle = false;
            Toast.makeText(this, R.string.ble_os_version_low, Toast.LENGTH_LONG).show();
        } else {
//            // 检查当前手机是否支持ble 蓝牙
//            if (!getPackageManager().hasSystemFeature( PackageManager.FEATURE_BLUETOOTH_LE)) {
//                Toast.makeText(this, R.string.ble_not_supported,Toast.LENGTH_LONG).show();
//                supportBle = false;
//            } else {
//        }
        	mBluetoothManager = (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE);
        	if (mBluetoothManager != null) {
        		mBluetoothAdapter = mBluetoothManager.getAdapter();
        		if (mBluetoothAdapter != null) {
        			enable = mBluetoothAdapter.isEnabled();
        			if (!enable) {
        				Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        				((Activity) mContext).startActivityForResult(enableBtIntent,REQUEST_ENABLE_BT_CLICK);
        			}else{
//        				mContext.startService(new Intent(mContext, BleService.class));
        				supportBle = true;
        			}
        		} else {
        			supportBle = false;
        		}
        	}else {
        		supportBle = false;
        	}
        }
      //注册蓝牙接收器
      		if(supportBle){
        	testStatus += "蓝牙可用\n";
        	testStatusTextView.setText(testStatus);
      			mlzApplication.putGlobalVariable("supportBle", "supportBle");	
      		}
	}
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == REQUEST_ENABLE_BT_CLICK && resultCode == Activity.RESULT_CANCELED) {
//			Toast.makeText(mContext, R.string.ble_not_supported, Toast.LENGTH_LONG).show();
			supportBle = false;
			specDetectFragment.onActivityResult(requestCode, resultCode, data);
			return;
		}else if(requestCode == Constants.SPEC_LOGIN_REQUEST_CODE ||
				requestCode == Constants.SPEC_SETTING_MINE_REQUEST_CODE||
				requestCode == Constants.REQUEST_NO_NET_REQUEST_CODE ||
				requestCode == Constants.SPEC_SETTING_LIST_REQUEST_CODE){
			specSettingFragment.onActivityResult(requestCode, resultCode, data);
		}else if (requestCode == REQUEST_ENABLE_BT_CLICK && resultCode == Activity.RESULT_OK){
			mGattUpdateReceiver = specDetectFragment.new BleBroadcastReceiver();
			mContext.registerReceiver(mGattUpdateReceiver,makeGattUpdateIntentFilter());
			supportBle = true;
			specDetectFragment.onActivityResult(requestCode, resultCode, data);
		}
	}
	
	
	private static IntentFilter makeGattUpdateIntentFilter() {
		final IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
		intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
		intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
		intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
		intentFilter.addAction(BluetoothLeService.SHOW_SCAN_BTN);
		intentFilter.addAction(BluetoothLeService.HIDE_SCAN_BTN);
		return intentFilter;
	}
	
	
	
	
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		//反注册蓝牙接收器
		if (supportBle && !receiverReleased && mGattUpdateReceiver != null) {
			receiverReleased = true;
			unregisterReceiver(mGattUpdateReceiver);
		}
	}
	
	
	 //************************************** service 开始

	@Override
	public void unBindService() {
		// TODO Auto-generated method stub
		if(isServiceReg) {
			unbindService(mServiceConnection);
			isServiceReg = false;
		}
	}


	@Override
	public void mConnect(boolean isConnect) {
		mConnected = isConnect;
		if(!isConnect) {
			try {
				if (!receiverReleased) {
					receiverReleased = true;
					unregisterReceiver(mGattUpdateReceiver);
				}
				if (isServiceReg && mServiceConnection != null) {
					isServiceReg = false;
					unbindService(mServiceConnection);
				}
				sendBroadcast(new Intent(BluetoothLeService.SHOW_SCAN_BTN));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void getBleData() {
		Thread thread = new Thread(new Runnable() {
			@SuppressLint("NewApi")
			@Override
			public void run() {
				while (mConnected) {
					if (mBluetoothLeService == null){
						return;
					}
					final BluetoothGattCharacteristic characteristic = getCharacteristic(mBluetoothLeService.getSupportedGattServices());
					if (characteristic != null) {
						final int charaProp = characteristic.getProperties();
						if ((charaProp & BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
							mBluetoothLeService.readCharacteristic(characteristic);
						}
					}
					try {
						Thread.sleep(60);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		});
		thread.start();
	}


	
	@Override
	public void reScan4Device() {
		// TODO Auto-generated method stub
		if (receiverReleased) {
			registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
			receiverReleased = false;
		}
		if ((mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled()) || mBluetoothAdapter==null) {
		} else {
			scanLeDevice(true);
		}
	}
	
	
	
	
	
	
    private String mDeviceAddress;
	private BluetoothLeService mBluetoothLeService;
	private Activity activity;

	private boolean isServiceReg = false; // mServiceConnection是否已绑定
	private static boolean receiverReleased = false; // mGattUpdateReceiver是否已释放注册
//	private boolean isSupportBLE;


	
    private boolean mConnected = false;	
	private boolean mScanning = false;	
	private Handler mHandler = new Handler();
	
//	private final int DEVICE_DIS_CONNECT = 103;
	
	 @SuppressLint("NewApi")
	 public void scanLeDevice(final boolean enable) {
		 sendBroadcast(new Intent(BluetoothLeService.HIDE_SCAN_BTN));
		 if (enable) {
			 // 扫描十秒钟后停止
	            mHandler.postDelayed(new Runnable() {
	                @Override
	                public void run() {
						boolean isConnect = mBluetoothLeService.connect(mDeviceAddress);
	                    if(mScanning ==true && !isConnect){
	                    	//TODO 应该判断蓝牙连接成功决定是否发送广播
	                    	sendBroadcast(new Intent(BluetoothLeService.SHOW_SCAN_BTN));
	                        mScanning = false;
	                        //这里必须用getBluetoothAdapter()，引文直接mBluetoothAdapter会报错
	                        mBluetoothAdapter.stopLeScan(mLeScanCallback);
	                    }
	                }
	            }, 10*1000);
			 mScanning = true;
			 mBluetoothAdapter.startLeScan(mLeScanCallback);
		 } else {
			 mScanning = false;
			 mBluetoothAdapter.stopLeScan(mLeScanCallback);
		 }
	 }

	    // Device scan callback.
	 @SuppressLint("NewApi")
	 private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
		 
		 @Override
		 public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
			 Runnable rn = new Runnable() {
				 
				 @Override
				 public void run() {
					 try {
						 if(device!=null && device.getName()!=null){
						 	testStatus += "搜索到蓝牙\n";
						 	runOnUiThread(new Runnable() {
								@Override
								public void run() {
									testStatusTextView.setText(testStatus);
								}
							});
//							 Log.e("=========","device.getName: "+device.getName());
							 if(BluetoothLeService.PERIPHERAL_DEVICE_SERVICE_NAME.equals(device.getName())){
								 if (mScanning) {
									 mBluetoothAdapter.stopLeScan(mLeScanCallback);
									 mScanning = false;
								 }
								 setmDeviceAddress(device.getAddress());
								 boolean isConnect = mBluetoothLeService.connect(mDeviceAddress);
								 isServiceReg = true;
								 if(isConnect){
									 testStatus += "蓝牙连接成功\n";
								 }else {
									 testStatus += "蓝牙连接失败\n";
								 }
								 runOnUiThread(new Runnable() {
									 @Override
									 public void run() {
										 testStatusTextView.setText(testStatus);
									 }
								 });
								 isServiceReg = true;
							 }
						 }
					 } catch (Exception e) {
						 e.printStackTrace();
					 }
					 
				 }
			 };
			 rn.run();
		 }
	 };

	 // Code to manage Service lifecycle.
	 public final ServiceConnection mServiceConnection = new ServiceConnection() {
		 
		 @Override
		 public void onServiceConnected(ComponentName componentName, IBinder service) {
			 mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
			 if (!mBluetoothLeService.initialize()) {
//				 finish();
				 Toast.makeText(activity,"蓝牙不可用",Toast.LENGTH_SHORT).show();
			 }

		 }
		 
		 @Override
		 public void onServiceDisconnected(ComponentName componentName) {
			 mBluetoothLeService = null;
			 isServiceReg = false;
		 }
	 };
	 
	 public void setmDeviceAddress(String address) {
		 mDeviceAddress = address;
	 }
	 
	 
	 @SuppressLint("NewApi")
	private BluetoothGattCharacteristic getCharacteristic(List<BluetoothGattService> gattServices) {
			if (gattServices == null)
				return null;
			for (BluetoothGattService gattService : gattServices) {
				String suuid = gattService.getUuid().toString();
				if (suuid.substring(4, 8).endsWith("1600")) {
					return gattService.getCharacteristic(UUID.fromString("00001601-0000-1000-8000-00805f9b34fb"));
				}
			}
			return null;
		}
	 
    //************************************** service 结束
}
